package com.peng.community.controller;

import com.peng.community.annotation.LoginRequire;
import com.peng.community.constant.CommunityConstant;
import com.peng.community.entity.Event;
import com.peng.community.entity.Page;
import com.peng.community.entity.User;
import com.peng.community.event.EventProducer;
import com.peng.community.service.UserService;
import com.peng.community.service.impl.FollowService;
import com.peng.community.util.CommunityUtils;
import com.peng.community.util.HostHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;

@Controller
@Slf4j
public class FollowController implements CommunityConstant {

    @Autowired
    HostHolder hostHolder;

    @Autowired
    FollowService followService;

    @Autowired
    EventProducer eventProducer;

//    @LoginRequire
    @PostMapping("/follow")
    @ResponseBody
    public String follow(int entityType, int entityId) {
        User user = hostHolder.getUser();
        if (user == null) {
            return "redirect:/site/login";
        }
        followService.follow(user.getId(),entityType,entityId);

        //关注才对主人发通知
        Event event = new Event()
                .setEntityId(entityId)
                .setUserId(user.getId())
                .setTopic(TOPIC_LIKE)
                .setEntityUserId(user.getId()) //当前只支持关注人
                .setEntityType(entityType);
        eventProducer.send(event);

        return CommunityUtils.toJsonString(0,"已关注" );
    }

//    @LoginRequire
    @PostMapping("/unfollow")
    @ResponseBody
    public String unfollow(int entityType, int entityId) {
        User user = hostHolder.getUser();
        if (user == null) {
            return "redirect:/site/login";
        }
        followService.unfollow(user.getId(),entityType,entityId);

        return CommunityUtils.toJsonString(0,"已取消关注");
    }

    @Autowired
    UserService userService;

    @GetMapping("/followers/{userId}")
    public String getFollowers(@PathVariable("userId")int userId, Page page, Model model) {
        User user = userService.findUserById(userId);
        model.addAttribute("user",user);

        page.setLimit(5);
        page.setPath("/followers/" + userId);
        page.setRows((int)followService.findFollowerCount(ENTITY_TYPE_USER, userId));

        List<Map<String, Object>> followers = followService.getFollowerList(userId, page.getOffset(), page.getLimit());

        log.info("被关注列表:{}", followers.toString());

        //设置每个用户是否可以关注
        for (Map<String, Object> map : followers) {
            User u = (User)map.get("user");
            map.put("hasFollowed",hasFollowed(u.getId()));
        }

        model.addAttribute("users", followers);

        return "/site/follower";
    }

    @GetMapping("/followees/{userId}")
    public String getFollowees(@PathVariable("userId")int userId, Page page, Model model) {
        User user = userService.findUserById(userId);
        model.addAttribute("user",user);

        page.setLimit(5);
        page.setPath("/followees/" + userId);
        page.setRows((int)followService.findFolloweeCount(user.getId(), ENTITY_TYPE_USER));

        List<Map<String, Object>> followees = followService.getFolloweeList(userId, page.getOffset(), page.getLimit());

        log.info("关注者列表:{}", followees.toString());
        //设置每个用户是否可以关注
        for (Map<String, Object> map : followees) {
            User u = (User)map.get("user");
            map.put("hasFollowed",hasFollowed(u.getId()));
        }

        model.addAttribute("users", followees);

        return "/site/followee";
    }

    private boolean hasFollowed(int userId) {
        User user = hostHolder.getUser();
        if (user == null) {
            throw new IllegalArgumentException("用户没有登录");
        }
       return followService.hasFollowed(user.getId(), ENTITY_TYPE_USER, userId);
    }

}
